
const UserModel =require("../model/user");
const crypto = require("crypto");
module.exports={
    register:(req,resp,next)=>{
        let {username, password} = req.body;
        password = crypto.createHash("md5").update(password).digest("hex");
        //插入数据库
        UserModel.save({username, password}).then(docs => {
          resp.json({
            "res_code": 1,
            "res_message" : "注册成功"
          });
        }).catch(() => {
          resp.json({
            "res_code": 0,
            "res_message" : "注册失败,该用户名已被注册"
          });
        })
},
    login:(req,resp,next)=>{
      let {username, password} = req.body;
      password = crypto.createHash("md5").update(password).digest("hex");
      //查找数据库
      UserModel.find({password,username}).then(docs=>{
        if(docs.length>=1){
          //存session
          req.session = {
            isLogin: true,
            user: docs
          };
          resp.json({
            "res_code":1,
            "res_message":"登陆成功"
          })
        }else{
          resp.json({
            "res_code":0,
            "res_message":"登陆失败,用户名或密码错误"
          })
        }
      }).catch(()=>{
        resp.json({
          "res_code":0,
          "res_message":"网络连接错误"
        })
      }
      )
    },
    isLogin: (req, resp, next) => {
      // 取session
      if(req.session.isLogin){
        resp.json({
          res_code: 1,
          res_body: {
            username: req.session.user[0].username
          }
        });
      }else{
        resp.json({
          res_code: 0,
          res_body: null
        });
      }
    },
    logout: (req, res, next) => {
      req.session = null;
      res.json({
        res_code : 1,
        res_message: "退出成功"
      })
    }

}